/**
 * 
 */
package com.excilys.dao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.hibernate.Hibernate;
import org.springframework.stereotype.Repository;

import com.excilys.model.Account;
import com.excilys.model.User;

/**
 * 
 * DAO for a user
 * 
 * @author excilys dev : VP, NT
 * 
 */

@Repository
public class UserDAOHibernateImpl implements IUserDAO {

	org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(UserDAOHibernateImpl.class);

	@PersistenceContext
	public EntityManager entityManager;

	/**
	 * {@inheritDoc}
	 */
	public User getUserByLogin(String myUserLogin) {
		Query myQuery = entityManager.createQuery("From User where userLogin= :userLogin");
		myQuery.setParameter("userLogin", myUserLogin);
		User resultUser = (User) myQuery.getSingleResult();
		Hibernate.initialize(resultUser.getUserListAccounts());
		Hibernate.initialize(resultUser.getUserTargetAccounts());
		return resultUser;
	}

	@Override
	public void addTargetAccountToUser(User u, Account a) {
		u.addTargetAccount(a);
		entityManager.merge(a);
		entityManager.merge(u);
	}

	@Override
	public void persistOneUser(User user) {
		entityManager.persist(user);
	}

}
